<template>
  <div class="view-content dispatch_info">
    <div class="bk_title">
      <div class="left">
        <div class="top">
          <div class="title_icon" />
          <p>统一布控</p>
        </div>
        <p>{{ moment().format('YYYY年MM月DD日 HH:mm:ss') }}</p>
      </div>
      <div class="right">
        <el-button type="primary" @click="handleSubmit(2)" v-show="!disable">
          保存
        </el-button>
        <el-button type="primary" @click="handleSubmit(1)" v-show="!disable">
          完成
        </el-button>
        <!-- <el-button type="info">
          继续布控
        </el-button> -->
        <el-button type="info" @click="cancelDispatch">
          取消
        </el-button>
      </div>
    </div>
    <div class="bk_type">
      <div class="title">
        <div class="cube" />
        <p>选择布控类型</p>
      </div>
      <el-radio-group v-model="dataForm.type" :disabled="disable" class="radio_group">
        <el-radio :label="'person'">
          人证布控
        </el-radio>
        <el-radio :label="'face'">
          人脸布控
        </el-radio>
        <el-radio :label="'car'">
          车辆布控
        </el-radio>
      </el-radio-group>
    </div>
    <div class="bk_info">
      <div class="title">
        <div class="cube" />
        <p>基本信息</p>
      </div>
      <el-form
        :model="dataForm"
        label-width="120px"
        ref="rzForm"
        class="formStyle"
        v-show="dataForm.type==='person'"
        :rules="personRules"
        :disabled="disable"
      >
        <el-form-item label="布控类型" prop="type">
          {{ types[dataForm.type] }}
        </el-form-item>
        <el-form-item label="布控名称" prop="bkName">
          <el-input v-model="dataForm.bkName" placeholder="请输入布控名称" />
        </el-form-item>
        <el-form-item label="身份证号" prop="num">
          <el-input v-model="dataForm.num" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="dataForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="dataForm.gender">
            <el-radio :label="0">
              男性
            </el-radio>
            <el-radio :label="1">
              女性
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="民族" prop="nation">
          <el-select v-model="dataForm.nation">
            <el-option v-for="(t,i) in store.state.dictionary.nation" :key="'nation_'+i" :value="t.value" :label="t.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="住址" prop="address">
          <el-input v-model="dataForm.address" placeholder="请输入住址" />
        </el-form-item>
        <el-form-item label="布控原因" prop="reason">
          <el-input v-model="dataForm.reason" placeholder="请输入布控原因" />
        </el-form-item>
        <el-form-item label="有效期开始" prop="startTime">
          <el-date-picker
            placeholder="开始时间"
            type="datetime"
            v-model="dataForm.startTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width:100%"
          />
        </el-form-item>
        <el-form-item label="有效期结束" prop="endTime">
          <el-date-picker
            placeholder="开始时间"
            type="datetime"
            v-model="dataForm.endTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width:100%"
          />
        </el-form-item>
        <el-form-item label="布控范围" prop="areaCode">
          <el-cascader
            :options="store.getters.getAreaList"
            v-model="dataForm.areaCode"
            :props="{
              checkStrictly: true,
              value: 'code',
              label: 'name'
            }"
            placeholder="请选择组织机构"
            clearable
          />
        </el-form-item>
        <el-form-item label="处置措施：" prop="action">
          <el-select v-model="dataForm.action">
            <el-option v-for="(t,i) in store.state.dictionary.action" :key="'action_'+i" :value="t.value" :label="t.label" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-form
        :model="dataForm"
        label-width="120px"
        ref="rlForm"
        class="formStyle"
        v-show="dataForm.type==='face'"
        :rules="faceRules"
        :disabled="disable"
      >
        <el-form-item label="布控类型" prop="type">
          {{ types[dataForm.type] }}
        </el-form-item>
        <el-form-item label="布控名称" prop="bkName">
          <el-input v-model="dataForm.bkName" placeholder="例如：特大盗抢案" />
        </el-form-item>
        <el-form-item label="选择照片" prop="img">
          <input
            type="file"
            ref="upload_img"
            id="upload_img"
            v-show="false"
            accept="image/png, image/jpeg"
            @change="uploadFileImg"
          >
          <div class="file_list">
            <div class="file_img" v-if="imgFile.url || dataForm.img">
              <div class="upload_info">
                <el-image :src="imgFile.url || dataForm.img" :preview-src-list="[imgFile.url || dataForm.img]" hide-on-click-modal style="width: 100px;height:140px;">
                  <template #error>
                    <div class="imgP">
                      <SvgIcon font="renyuan-shi" :size="90" class="icon" />
                    </div>
                  </template>
                </el-image>
                <p class="close" @click="removeImage()">
                  <el-icon>
                    <Close />
                  </el-icon>
                </p>
              </div>
            </div>
            <div class="file_img" v-else>
              <div class="upload_info" @click="openFile">
                <div class="imgP">
                  <SvgIcon font="renyuan-shi" :size="90" class="icon" />
                </div>
                <p>请选择图片</p>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="身份证号" prop="num">
          <el-input v-model="dataForm.num" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="dataForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="dataForm.gender">
            <el-radio :label="0">
              男性
            </el-radio>
            <el-radio :label="1">
              女性
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="民族" prop="nation">
          <el-select v-model="dataForm.nation">
            <el-option v-for="(t,i) in store.state.dictionary.nation" :key="'nation_'+i" :value="t.value" :label="t.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="住址" prop="address">
          <el-input v-model="dataForm.address" placeholder="请输入住址" />
        </el-form-item>
        <el-form-item label="布控原因" prop="reason">
          <el-input v-model="dataForm.reason" placeholder="请输入布控原因" />
        </el-form-item>
        <el-form-item label="有效期开始" prop="startTime">
          <el-date-picker
            placeholder="开始时间"
            type="datetime"
            v-model="dataForm.startTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width:100%"
          />
        </el-form-item>
        <el-form-item label="有效期结束" prop="endTime">
          <el-date-picker
            placeholder="开始时间"
            type="datetime"
            v-model="dataForm.endTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width:100%"
          />
        </el-form-item>
        <el-form-item label="布控范围" prop="areaCode">
          <el-cascader
            :options="store.getters.getAreaList"
            v-model="dataForm.areaCode"
            :props="{
              checkStrictly: true,
              value: 'code',
              label: 'name'
            }"
            placeholder="请选择组织机构"
            clearable
          />
        </el-form-item>
        <el-form-item label="阈值" prop="yuzhi">
          <el-input v-model="dataForm.yuzhi" placeholder="请输入阈值" />
        </el-form-item>
        <el-form-item label="处置措施：" prop="action">
          <el-select v-model="dataForm.action">
            <el-option v-for="(t,i) in store.state.dictionary.action" :key="'action_'+i" :value="t.value" :label="t.label" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-form
        :model="dataForm"
        label-width="120px"
        ref="clForm"
        class="formStyle"
        v-show="dataForm.type==='car'"
        :rules="carRules"
        :disabled="disable"
      >
        <el-form-item label="布控类型" prop="type">
          {{ types[dataForm.type] }}
        </el-form-item>
        <el-form-item label="布控名称" prop="bkName">
          <el-input v-model="dataForm.bkName" placeholder="请输入布控名称" />
        </el-form-item>
        <el-form-item label="车牌号码" prop="num">
          <el-input v-model="dataForm.num" placeholder="请输入车牌号码" />
        </el-form-item>
        <el-form-item label="车牌颜色" prop="cpys">
          <el-select v-model="dataForm.cpys">
            <el-option v-for="(t,i) in store.state.dictionary.nation" :key="'nation_'+i" :value="t.value" :label="t.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="车辆类型" prop="carType">
          <el-select v-model="dataForm.carType">
            <el-option v-for="(t,i) in store.state.dictionary.carType" :key="'nation_'+i" :value="t.value" :label="t.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="车身颜色" prop="csys">
          <el-select v-model="dataForm.csys">
            <el-option v-for="(t,i) in store.state.dictionary.carColor" :key="'nation_'+i" :value="t.value" :label="t.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="布控范围" prop="areaCode">
          <el-cascader
            :options="store.getters.getAreaList"
            v-model="dataForm.areaCode"
            :props="{
              checkStrictly: true,
              value: 'code',
              label: 'name'
            }"
            placeholder="请选择组织机构"
            clearable
          />
        </el-form-item>
        <el-form-item label="布控原因" prop="reason">
          <el-input v-model="dataForm.reason" placeholder="请输入布控原因" />
        </el-form-item>
        <el-form-item label="有效期开始" prop="startTime">
          <el-date-picker
            placeholder="开始时间"
            type="datetime"
            v-model="dataForm.startTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width:100%"
          />
        </el-form-item>
        <el-form-item label="有效期结束" prop="endTime">
          <el-date-picker
            placeholder="开始时间"
            type="datetime"
            v-model="dataForm.endTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width:100%"
          />
        </el-form-item>
        <el-form-item label="处置措施：" prop="action">
          <el-select v-model="dataForm.action">
            <el-option v-for="(t,i) in store.state.dictionary.action" :key="'action_'+i" :value="t.value" :label="t.label" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="files_record">
      <div class="title">
        <div class="cube" />
        <p>附件记录</p>
        <el-button type="primary" @click="addFiles" class="add_button" v-show="!disable">
          新增附件
        </el-button>
      </div>
      <table-form
        ref="fileTable"
        class="eltable"
        :index="false"
        :columns="columns"
        :load="load"
        :menus="menus"
        :page="true"
        :tools="false"
        height="300px"
        :auto-load="false"
        @event="tableEvent"
      />
    </div>
    <div class="warning_link">
      <div class="title">
        <div class="cube" />
        <p>预警联动</p>
        <el-button type="primary" @click="addLinks" class="add_button" v-show="!disable">
          新增联动
        </el-button>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick" class="eltabs">
        <el-tab-pane label="用户联动" name="user" />
        <el-tab-pane label="系统联动" name="system" />
      </el-tabs>
      <table-form
        ref="userTable"
        class="eltable"
        v-if="activeName==='user'"
        :index="false"
        :columns="columnsUser"
        :load="loadUser"
        :page="true"
        height="300px"
        :tools="false"
        :menus="userMenus"
        @event="userTableEvent"
      />
      <table-form
        ref="systemTable"
        class="eltable"
        v-if="activeName==='system'"
        :index="false"
        :columns="columnsSystem"
        :load="loadSystem"
        :page="true"
        height="300px"
        :tools="false"
      />
    </div>
    <div class="time-line">
      <div class="title">
        <div class="cube" />
        <p>历史记录</p>
      </div>
      <div style="text-align: center;margin: 20px 0;display: flex;flex-flow:column nowrap;" v-show="historyData.length===0">
        <img src="@/assets/retrieval/noData.png" style="width: 100px;height: 100px;margin:0 auto;">
        <p style="font-size: 8px;margin-top: 10px">
          暂无数据
        </p>
      </div>
      <el-timeline>
        <el-timeline-item v-for="(t,i) in historyData" :key="'car'+i" :timestamp="t.time" placement="top">
          <el-card>
            <div class="time_card">
              <div class="img">
                <el-image :src="t.img" :preview-src-list="[t.img]" hide-on-click-modal style="width: 100%;height:100%;">
                  <template #error>
                    <div class="imgP">
                      <SvgIcon font="renyuan-shi" :size="90" class="icon" />
                    </div>
                  </template>
                </el-image>
              </div>
              <div class="info">
                <h4>{{ t.account }}</h4>
                <p>{{ t.content }}</p>
              </div>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </div>
    <dialog-form v-model="addFileObj.visible" title="新增附件" :confirm="fileSubmit" width="35%">
      <el-form :model="addFileObj" label-width="120px">
        <el-form-item label="附件名称">
          <el-input v-model="addFileObj.fileName" placeholder="请输入附件名称" />
        </el-form-item>
        <el-form-item label="上传附件">
          <UploadFile ref="uploadFile" v-model="addFileObj.fileUrl" :len="1" accept="img" />
        </el-form-item>
      </el-form>
    </dialog-form>
    <dialog-form v-model="addUserLink.visible" title="新增人员联动" :confirm="userSubmit" width="35%">
      <el-form :model="addFileObj" label-width="120px">
        <el-form-item label="选择联动用户">
          <el-select v-model="addUserLink.username" placeholder="请选择联动用户">
            <el-option v-for="(t,i) in userLists" :key="'user_'+i" :value="t.username" :label="t.name" />
          </el-select>
        </el-form-item>
      </el-form>
    </dialog-form>
    <dialog-form v-model="addSystemLink.visible" title="新增系统联动" :confirm="systemSubmit" width="35%">
      <el-form :model="addFileObj" label-width="120px">
        <el-form-item label="附件名称">
          <el-input v-model="addFileObj.fileName" placeholder="请输入附件名称" />
        </el-form-item>
        <el-form-item label="上传附件">
          <UploadFile ref="uploadFile" v-model="addFileObj.fileUrl" :len="1" accept="img" />
        </el-form-item>
      </el-form>
    </dialog-form>
  </div>
</template>

<script lang="ts" setup>
import { TableColumnsProps, MenuProps } from '@/components/Table/types/tableForm'
import { useStore } from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'
import { onMounted, ref, nextTick } from 'vue'
import { Close } from '@element-plus/icons'
import { addControl, editControl, addFile, deleteFile, bkLogs, fileList, addTellUsers, tellUsers, deleteTellUsers } from '@/api/control'
import { isIdcard, isPlateNumber } from '@/utils/validate'
import { useRoute, useRouter } from 'vue-router'
import { fileRandomFid } from '@/api/upload'
import UploadFile from '@/components/Upload/UploadFile.vue'
import { userList } from '@/api/system'
import { downloadFile } from '@/utils/utils'

// 参数
interface ImgList {
  url?: any
  files?: any
}
const types = {
  person: '人证布控',
  face: '人脸布控',
  car: '车辆布控'
}
const store = useStore()
const initDatas = () => ({
  dataForm: {
    id: null,
    type: 'person',
    name: '',
    bkName: '',
    num: '',
    gender: 0,
    nation: '',
    address: '',
    reason: '',
    startTime: '',
    endTime: '',
    areaCode: '',
    csys: '',
    carType: '',
    cpys: '',
    img: '',
    yuzhi: 80,
    action: ''
  },
  columns: [{
    prop: 'createDate',
    label: '上传时间'
  }, {
    prop: 'fileName',
    label: '附件名称'
  }, {
    prop: 'type',
    label: '附件格式',
    formatter: row => row.fileUrl ? row.fileUrl.split('.')[row.fileUrl.split('.').length - 1] : '未知'
  }, {
  //   prop: 'size',
  //   label: '文件大小'
  // }, {
    prop: 'addUsername',
    label: '上传人员'
  }] as TableColumnsProps[],
  menus: [{
    name: '下载',
    event: 'download',
    type: 'primary'
  }, {
    name: '删除',
    event: 'del',
    type: 'danger'
  }] as MenuProps[],
  columnsUser: [{
    prop: 'account',
    label: '登录账号'
  }, {
    prop: 'username',
    label: '姓名'
  }, {
    prop: 'orgName',
    label: '所属组织'
  }, {
    prop: 'areaName',
    label: '行政区划'
  }, {
    prop: 'phone',
    label: '联系电话'
  }] as TableColumnsProps[],
  userMenus: [{
    name: '删除',
    event: 'del',
    type: 'danger'
  }] as MenuProps[],
  columnsSystem: [{
    prop: 'name',
    label: '系统名称'
  }, {
    prop: 'link',
    label: '是否联动'
  }] as TableColumnsProps[],
  historyData: [] as any[],
  imgFile: {} as ImgList,
  personRules: {
    bkName: [{ required: true, message: '请输入布控名称', trigger: 'blur' }],
    num: [
      { required: true, message: '请输入身份证号', trigger: 'blur' },
      { validator: isIdcard, trigger: 'blur' }
    ],
    name: [{ required: true, message: '请输入人员姓名', trigger: 'blur' }],
    nation: [{ required: true, message: '请输入民族', trigger: 'blur' }],
    reason: [{ required: true, message: '请输入布控原因', trigger: 'blur' }],
    startTime: [{ required: true, message: '请输入有效期', trigger: 'blur' }],
    endTime: [{ required: true, message: '请输入有效期', trigger: 'blur' }],
    areaCode: [{ required: true, message: '请选择行政区划', trigger: 'blur' }],
    action: [{ required: true, message: '请选择处置措施', trigger: 'blur' }]
  },
  faceRules: {
    bkName: [{ required: true, message: '请输入布控名称', trigger: 'blur' }],
    num: [
      { required: true, message: '请输入身份证号', trigger: 'blur' },
      { validator: isIdcard, trigger: 'blur' }
    ],
    name: [{ required: true, message: '请输入人员姓名', trigger: 'blur' }],
    nation: [{ required: true, message: '请输入民族', trigger: 'blur' }],
    reason: [{ required: true, message: '请输入布控原因', trigger: 'blur' }],
    startTime: [{ required: true, message: '请输入有效期', trigger: 'blur' }],
    endTime: [{ required: true, message: '请输入有效期', trigger: 'blur' }],
    areaCode: [{ required: true, message: '请选择行政区划', trigger: 'blur' }],
    action: [{ required: true, message: '请选择处置措施', trigger: 'blur' }],
    yuzhi: [{ required: true, message: '请输入阈值', trigger: 'blur' }]
  },
  carRules: {
    bkName: [{ required: true, message: '请输入布控名称', trigger: 'blur' }],
    num: [
      { required: true, message: '请输入身份证号', trigger: 'blur' },
      { validator: isPlateNumber, trigger: 'blur' }
    ],
    reason: [{ required: true, message: '请输入布控原因', trigger: 'blur' }],
    startTime: [{ required: true, message: '请输入有效期', trigger: 'blur' }],
    endTime: [{ required: true, message: '请输入有效期', trigger: 'blur' }],
    areaCode: [{ required: true, message: '请选择行政区划', trigger: 'blur' }],
    action: [{ required: true, message: '请选择处置措施', trigger: 'blur' }]
  },
  addFileObj: {
    id: null,
    fileName: '',
    fileUrl: '',
    visible: false
  },
  addUserLink: {
    username: '',
    visible: false
  },
  addSystemLink: {
    visible: false
  },
  files: [] as any,
  tellUser: [] as any
})

const dataForm = ref(initDatas().dataForm)
const columns = ref(initDatas().columns)
const menus = ref(initDatas().menus)
const userMenus = ref(initDatas().userMenus)
const columnsUser = ref(initDatas().columnsUser)
const columnsSystem = ref(initDatas().columnsSystem)
const historyData = ref(initDatas().historyData)
const addFileObj = ref(initDatas().addFileObj)
const addUserLink = ref(initDatas().addUserLink)
const addSystemLink = ref(initDatas().addSystemLink)
const files = ref(initDatas().files)
const tellUser = ref(initDatas().tellUser)
// 表单验证
const personRules = ref(initDatas().personRules)
const faceRules = ref(initDatas().faceRules)
const carRules = ref(initDatas().carRules)
// 查询数据列表
const activeName = ref('')
const load = async () => {
  let data = {
    totalElements: 0,
    content: []
  }
  if (dataForm.value.id) {
    data = await fileList(dataForm.value.id)
  } else {
    data = files.value
  }
  return data
}
// 查询数据列表
const loadUser = async () => {
  let data = {
    totalElements: 0,
    content: []
  }
  if (dataForm.value.id) {
    data = await tellUsers(dataForm.value.id)
  } else {
    data = tellUser.value
  }
  return data
}
// 查询数据列表
const loadSystem = async () => {
  const data = {
    totalElements: 0,
    content: []
  }
  return Promise.resolve(data)
}

// 操作栏事件
const tableEvent = async (event: MenuProps['event'], row: any, index?: number) => {
  switch (event) {
    // 详情
    case 'download':
      downloadFile(row.fileUrl)
      break
    case 'del':
      if (dataForm.value.id) {
        ElMessageBox({
          title: '提示',
          message: `确定删除【${row.fileName}】附件`,
          type: 'warning',
          showCancelButton: true,
          cancelButtonText: '取消',
          confirmButtonText: '确认',
          center: true
        }).then(async () => {
          await deleteFile(row.id)
          ElMessage.success('删除成功')
          reflushData()
        })
      } else {
        files.value.splice(index, 1)
      }
      break
  }
}
const userTableEvent = async (event: MenuProps['event'], row: any) => {
  switch (event) {
    // 详情
    case 'del':
      ElMessageBox({
        title: '提示',
        message: `确定删除【${row.username}】用户联动么`,
        type: 'warning',
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确认',
        center: true
      }).then(async () => {
        await deleteTellUsers(row.id)
        ElMessage.success('删除成功')
        reflushData()
      })
      break
  }
}
const handleClick = (val: any) => {
  activeName.value = val.props.name
}

// 图片上传相关
const upload_img = ref()
const imgFile = ref(initDatas().imgFile)
const uploadFileImg = async () => {
  const files = upload_img.value.files[0]
  const data = await fileRandomFid({ file: files, type: 'avatar' })
  dataForm.value.img = data
  imgFile.value = {
    url: data,
    files
  }
  upload_img.value.value = null
}
const removeImage = async () => {
  await ElMessageBox({
    title: '提示',
    message: '确定要删除这张图片吗？',
    type: 'warning',
    showCancelButton: true,
    cancelButtonText: '取消',
    confirmButtonText: '确认',
    center: true
  })
  imgFile.value = {}
  dataForm.value.img = ''
}
const openFile = () => {
  upload_img.value.click()
}

// 提交事件
const rzForm = ref()
const rlForm = ref()
const clForm = ref()
const handleSubmit = async (type: any) => {
  let valid = {} as any
  const params = dataForm.value
  const data = {
    type: params.type,
    bkName: params.bkName,
    num: params.num,
    areaCode: Array.isArray(params.areaCode) ? params.areaCode[params.areaCode.length - 1] : params.areaCode,
    reason: params.reason,
    startTime: params.startTime,
    endTime: params.endTime,
    action: params.action,
    status: type
  } as any
  switch (dataForm.value.type) {
    case 'person':
      // if (type === 1) {
      valid = await rzForm.value?.validate()
      // }
      data.name = params.name
      data.gender = params.gender
      data.nation = params.nation
      data.address = params.address
      break
    case 'face':
      // if (type === 1) {
      valid = await rlForm.value?.validate()
      // }
      data.name = params.name
      data.gender = params.gender
      data.nation = params.nation
      data.address = params.address
      data.img = params.img
      data.yuzhi = params.yuzhi
      break
    case 'car':
      // if (type === 1) {
      valid = await clForm.value?.validate()
      // }
      data.cpys = params.cpys
      data.carType = params.carType
      data.csys = params.csys
      break
  }
  if (!valid) return
  if (params.id) {
    await editControl(params)
    ElMessage.success('修改成功')
  } else {
    const res = await addControl(data)
    ElMessage.success('新增成功')
    files.value.forEach(async (t: { id: any }) => {
      t.id = res
      await addFile(t)
      addFileObj.value.visible = false
      reflushData()
    })
    tellUser.value.forEach(async (t: { bkid: any }) => {
      t.bkid = res
      await addTellUsers(t)
      addUserLink.value.visible = false
      reflushData()
    })
  }
}

// 取消
const router = useRouter()
const cancelDispatch = () => {
  if (router.hasRoute('dispatchInfo')) {
    const view = router.getRoutes().find(t => t.name === 'dispatchInfo')
    store.dispatch('delView', view)
    router.back()
  }
}

// 新增附件
const addFiles = () => {
  Object.assign(addFileObj.value, initDatas().addFileObj)
  addFileObj.value.id = dataForm.value.id
  addFileObj.value.visible = true
}
// 提交附件
const fileTable = ref()
const uploadFile = ref()
const fileSubmit = async () => {
  const params = addFileObj.value
  const avatar = uploadFile.value.getFiles()
  const data = {
    id: params.id,
    fileName: params.fileName || avatar.name,
    fileUrl: avatar.src,
    size: avatar.size
  }
  if (dataForm.value.id) {
    await addFile(data)
    ElMessage.success('新增成功')
    addFileObj.value.visible = false
    reflushData()
  } else {
    files.value.push(data)
    ElMessage.success('新增成功')
    addFileObj.value.visible = false
    reflushData()
  }
}

// 历史记录
const getLogs = async () => {
  if (dataForm.value.id) {
    const logs = await bkLogs(dataForm.value.id)
    historyData.value = logs
  }
}
// 刷新联动数据
const userTable = ref()
const reflushData = () => {
  fileTable.value.fetchData()
  userTable.value.fetchData()
  getLogs()
}

// 新增联动
const addLinks = () => {
  if (activeName.value === 'user') {
    Object.assign(addUserLink.value, initDatas().addUserLink)
    addUserLink.value.visible = true
  }
}

// 关联用户数据列表
const userLists = ref<any>([])
const initUsers = async () => {
  const res = await userList({ page: 0, size: 1000 })
  userLists.value = res.content
}

// 用户提交
const userSubmit = async () => {
  const params = addUserLink.value
  const user = userLists.value.find((t: { username: string }) => t.username === params.username)
  const data = {
    account: user.username,
    username: user.name,
    orgName: user.organName,
    areaName: user.areaName,
    phone: user.phone,
    bkid: dataForm.value.id
  }
  if (dataForm.value.id) {
    await addTellUsers(data)
    ElMessage.success('新增成功')
    addUserLink.value.visible = false
    reflushData()
  } else {
    tellUser.value.push(data)
    ElMessage.success('新增成功')
    addUserLink.value.visible = false
    reflushData()
  }
}

// 系统提交
const systemSubmit = async () => {

}

const route = useRoute()
const disable = ref(false)
onMounted(() => {
  if (JSON.stringify(route.query) !== '{}') {
    const type = route.query.type
    const data = JSON.parse(route.query.data!.toString())
    dataForm.value = data
    disable.value = type === 'detail'
    initUsers()
    activeName.value = 'user'
  }
  nextTick(() => {
    reflushData()
  })
})
</script>
<script lang="ts">
export default {
  name: 'DispatchInfo'
}
</script>

<style lang="scss" scoped>
.dispatch_info {
  background: var(--bk-title-bg-color);
  &::-webkit-scrollbar {
    display: none;
  }
  .bk_title {
    width: 100%;
    margin: 0 auto;
    height: 80px;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #8291A940;
    > .left {
      flex: 1;
      .top {
        height: 30px;
        display: flex;
        .title_icon {
          width: 30px;
          height: 30px;
          background: url('@/assets/control/icon.png') no-repeat;
          background-size: 100% 100%;
          margin: 5px 0 0 10px;
        }
        p {
          height: 40px;
          line-height: 40px;
          margin-left: 10px;
          font-size: 20px;
          font-weight: 700;
        }
      }
      p {
        height: 40px;
        line-height: 40px;
        margin-left: 20px;
      }
    }
    > .right {
      flex: 1;
      line-height: 80px;
      text-align: right;
      margin-right: 20px;
    }
  }
  .bk_type {
    width: 100%;
    margin: 0 auto;
    height: 120px;
    border-bottom: 1px solid #8291A940;
  }
  .bk_info {
    width: 100%;
    margin: 0 auto;
    height: auto;
    padding-bottom: 20px;
    margin-bottom: 20px;
    background: var(--bk-title-bg-color);
    border-bottom: 1px solid #8291A940;
  }
}
.title {
  display: flex;
  margin: 10px 0 0 10px;
  position: relative;
  .cube {
    width: 5px;
    height: 20px;
    background: #409EFF;
  }
  p {
    margin-left: 10px;
    font-weight: 700;
    font-size: 16px;
  }
  .add_button {
    position: absolute;
    right: 25px;
  }
}
.radio_group {
  width: 100%;
  justify-content: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
.formStyle {
  width: 30%;
  margin: 0 auto;
  margin-top: 20px;
}
.files_record {
  width: 100%;
  height: auto;
  display: flex;
  flex-direction: column;
  padding-bottom: 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid #8291A940;
}
.warning_link {
  width: 100%;
  height: auto;
  display: flex;
  flex-direction: column;
  padding-bottom: 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid #8291A940;
}
.el-timeline {
  margin: 20px 20px 0 20px;
}
.el-tabs .el-tabs__content {
  height: calc(100% - 40px)
}
.eltabs {
  margin: 0 20px;
}
.eltable {
  flex: 1;
  margin: 20px;
}
.file_img {
  width: 100%;
  height: 100%;
  margin-right: 10px;
  &:last-child {
    margin: 0;
  }
  .upload_info {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    border-radius: 5px;
    overflow: hidden;
    cursor: pointer;
    position: relative;
    .close {
      width: 15px;
      height: 15px;
      line-height: 10px;
      font-size: 15px;
      text-align: center;
      background: #d2d2d2;
      border-radius: 50%;
      position: absolute;
      top: 0;
      right: 0;
      cursor: pointer;
      color: red;
    }
  }
}
.time_card {
  display: flex;
  .info {
    flex: 0 0 80%;
    margin-left: 20px;
  }
  .img {
    width: 50px;
    height: 70px;
    .imgP {
      width: 50px;
      height: 70px;
      background: #8291A9;
      .icon {
        margin-left: -20px;
        margin-top: -8px;
        color: #263959;
      }
    }
  }
}
</style>

<style lang="scss">
html.dark .dispatch_info {
  --bk-title-bg-color: #283442;
  .el-table {
    --el-table-header-bg-color: #1F2935;
  }
}
</style>
